package com.sxhuayuan.parking.queue.rabbitmq.consumer;

import java.io.IOException;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.sxhuayuan.parking.compenent.RabbitMQConfig;
import com.sxhuayuan.parking.exception.MyException;
import com.sxhuayuan.parking.plugin.parking.ParkingPlugin;
import com.sxhuayuan.parking.queue.QueueService;
import com.sxhuayuan.parking.queue.msg.NotifyParkingLotMsg;
import com.sxhuayuan.parking.queue.msg.QueueMsg;
import com.sxhuayuan.parking.service.PluginService;
import com.sxhuayuan.parking.utils.SettingUtils;
import com.sxhuayuan.parking.utils.SpringUtils;

import lombok.extern.log4j.Log4j2;

/**
 * 通知第三方车场消费者
 * 
 * @author gy
 */
@Component("notifyParkingLotConsumer")
@RabbitListener(queues = RabbitMQConfig.QUEUE_DELAY_NOTIFY_PARKING_LOT)
@Log4j2
public class NotifyParkingLotConsumer {

	@Autowired
	QueueService queueService;

	@RabbitHandler
	public void handler(byte[] bytes, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
		QueueMsg msg = JSON.parseObject(bytes, QueueMsg.class);
		NotifyParkingLotMsg notify = JSON.parseObject(msg.getBody(), NotifyParkingLotMsg.class);
		PluginService pluginService = SpringUtils.getBean(PluginService.class);
		ParkingPlugin parkingPlugin = pluginService.getParkingPlugin(notify.getPluginId());
		boolean isNotifySuccess = false;
		try {
			if (SettingUtils.get().getIsDebug() && !parkingPlugin.isOpenNotifyWhileDebug()) {
				log.debug("测试模式，未开启回调");
				isNotifySuccess = true;
			} else {
				isNotifySuccess = parkingPlugin.notifyParkingFeeOrderSuccess(notify);
			}
		} catch (Exception e) {
			log.debug("通知车场失败:", e);
			if (e instanceof MyException) {
				notify.notifyFail();
				if (!notify.isNotifyTimeout()) {
					log.debug("未超时，重新加入队列: {}", notify.getLocalOrderSn());
				} else {
					log.debug("通知超时: {}", JSON.toJSONString(notify));
				}
			}
			channel.basicNack(tag, false, false);
		}
		if (isNotifySuccess) {
			log.debug("通知成功: {}", notify.getLocalOrderSn());
			channel.basicAck(tag, false);
		} else {
			log.debug("通知失败: {}", notify.getLocalOrderSn());
			channel.basicNack(tag, false, false);
		}
	}
}
